package com.share.device.emqx.callback;

import com.alibaba.fastjson.JSONObject;
import com.share.device.emqx.factory.MessageHandlerFactory;
import com.share.device.emqx.handler.MassageHandler;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;

import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class OnMessageCallback implements MqttCallback {
    @Autowired
    private MessageHandlerFactory messageHandlerFactory;

    @Override
    public void connectionLost(Throwable cause) {
        // 连接丢失后，一般在这里面进行重连
        System.out.println("连接断开，可以做重连");
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) {
        // subscribe后得到的消息会执行到这里面
        System.out.println("接收消息主题:" + topic);
        System.out.println("接收消息Qos:" + message.getQos());
        System.out.println("接收消息内容:" + new String(message.getPayload()));
        try {
            // 根据主题选择不同的处理逻辑
            MassageHandler massageHandler = messageHandlerFactory.getMassageHandler(topic);

//            String content = Arrays.toString(message.getPayload());
            String content = new String(message.getPayload());
            log.info(content);
            if(null != massageHandler) {
//                Map<String, Object> dataMap = new HashMap<>();
//                String[] keyValuePairs = content.split("\\|"); // 分割键值对
//                log.info(Arrays.toString(keyValuePairs));
//                for (String pair : keyValuePairs) {
//                    String[] kv = pair.split("=", 2); // 分割键和值（限制最多2部分）
//                    if (kv.length == 2) {
//                        log.info(kv[0] + "=" + kv[1]);
//                        dataMap.put(kv[0].trim(), kv[1].trim()); // 去除可能的空格
//                    }
//                }
//                log.warn(dataMap.toString());
//                log.warn(JSONObject.toJSONString(new JSONObject(dataMap)));
//                log.warn("最终dataMap大小: {}", dataMap.size()); // 确认是否有数据
//                JSONObject jsonObject = new JSONObject(dataMap);
                log.warn(JSONObject.parseObject(content).toString());
                massageHandler.handleMessage(JSONObject.parseObject(content));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("mqtt消息异常：{}", new String(message.getPayload()));
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());
    }
}